package com.deyinet.bdcms.controller;

import com.alibaba.fastjson.JSON;
import com.deyinet.bdcms.controller.dtoandapi.ConfApi;
import com.deyinet.bdcms.controller.dtoandapi.LinechartApi;
import com.deyinet.bdcms.controller.dtoandapi.MapDeviceApi;
import com.deyinet.bdcms.entity.Device;
import com.deyinet.bdcms.entity.Deviceconfig;
import com.deyinet.bdcms.entity.Devicedata;
import com.deyinet.bdcms.service.IDeviceConfigService;
import com.deyinet.bdcms.service.IDeviceService;
import com.deyinet.bdcms.service.IDevicedataService;
import com.deyinet.bdcms.tools.CheckNull;
import com.deyinet.bdcms.tools.RedisPoolUtils;
import com.deyinet.bdcms.tools.WebUtilify;
import com.deyinet.bdcms.tools.superUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/9/20 0020.
 */
@Controller
@RequestMapping(value = "/sysmanage/devicemonitor")
public class DevicemonitorController {
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDevicedataService devicedataService;
    @Autowired
    private IDeviceConfigService deviceConfigService;

    @RequestMapping(value = "/location", method = RequestMethod.GET)
    public void list() {
    }

    @RequestMapping(value = "/state", method = RequestMethod.GET)
    public void state() {
    }

    @RequestMapping(value = "/ipconfiguration")
    public void ipconfiguration() {
    }

    @RequestMapping(value = "/deviceMap")
    @ResponseBody
    public List<MapDeviceApi> deviceMap(HttpServletRequest request) throws ParseException {
        String deviceInfo = request.getParameter("deviceInfo");
        String deviceName = request.getParameter("deviceName");
        String ownerid = request.getParameter("deviceOwner");
        Jedis redis = null;
        List<MapDeviceApi> deviceApis = new ArrayList<>();
        Device device = new Device();
        if (!"".equals(deviceName)) {
            device.setDevicename(deviceName);
        }
        if (!"".equals(deviceInfo)) {
            device.setDeviceinfo(deviceInfo);
        }
        if (ownerid != null && !"".equals(ownerid)) {
            device.setOwnerid(Integer.valueOf(ownerid));
        }
        List<Device> a = deviceService.findMapDevice(device);
        try {
            redis = RedisPoolUtils.getJedisObject();
            for (Device dev : a) {
                String b = redis.hget(RedisPoolUtils.dbname, dev.getSn());
                if (b == null) {
                    continue;
                }
                MapDeviceApi deviceApi = JSON.parseObject(b, MapDeviceApi.class);
                deviceApi.setSn(dev.getSn());
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (CheckNull.check(deviceApi.getReportTime())) {
                    Timestamp reportTime = new Timestamp(format1.parse(deviceApi.getReportTime()).getTime());
                    Long reportCycle = Long.valueOf(deviceApi.getReportCycle() + 5) * 60000;
                    Long deltaT = System.currentTimeMillis() - reportTime.getTime();
                    if (deltaT > reportCycle) {
                        deviceApi.setCurrentStatus(5);
                    }
                }

                deviceApis.add(deviceApi);
            }
        } finally {
            redis.close();
        }
        return deviceApis;
    }

    @RequestMapping(value = "/deviceMapIni")
    @ResponseBody
    public List<MapDeviceApi> deviceMapIni(HttpServletRequest request) throws ParseException {
        Jedis redis = null;
        try {
            redis = RedisPoolUtils.getJedisObject();
            Map<String, String> map = redis.hgetAll(RedisPoolUtils.dbname);
            String s = JSON.toJSONString(map);
            System.out.println(s);
        } finally {
            redis.close();
        }
        return null;
    }

    @RequestMapping(value = "/deviceipConf")
    @ResponseBody
    public Map<String, String> deviceipConf(ConfApi confApi, HttpServletRequest request, HttpSession session) {
        Map<String, String> info = new HashMap<>();
        Integer s1 = superUser.getRoleId();

        if (WebUtilify.LoginUserinfo(request).getRoleId() != s1) {
            info.put("content", "您没有修改权限");
            info.put("Message", "error");
        }

        info.put("content", "配置成功");
        info.put("Message", "ok");
        Jedis redis = RedisPoolUtils.getJedisObject();
        Map<String, String> map = new HashMap<>();
        try {
            Pipeline p = redis.pipelined();
            String netString = confApi.getNetconfig();
            if (!netString.contains(":")) {
                info.put("content", "ip格式不对");
                info.put("Message", "error");
                return info;
            }
            String[] strings = netString.split(":");
            String ip = strings[0];
            String point = strings[1];
            if (!isIP(ip)) {
                info.put("content", "ip格式不对");
                info.put("Message", "error");
                return info;
            }
            if (!isInteger(point)) {
                info.put("content", "ip格式不对");
                info.put("Message", "error");
                return info;
            }
            confApi.setNetconfig(ip + "," + point);
            if (confApi.getAllDevices() != 0) {
                List<Device> list = deviceService.getList();
                for (Device dev : list) {
                    IPconfig(dev, confApi, map);
                }
            } else if (confApi.getAllDevices() == null) {
                info.put("content", "参数错误");
                info.put("Message", "error");
                return info;
            } else {
                Device device = deviceService.get(confApi.getSn());
                IPconfig(device, confApi, map);
            }
            p.hmset(RedisPoolUtils.fireConfig, map);
            p.sync();
            p.close();
        } catch (Exception ex) {
            info.put("content", "ip格式不对");
            info.put("Message", "error");
            return info;
        }
        return info;

    }

    @RequestMapping(value = "/linechartdata")
    @ResponseBody
    public List<LinechartApi> linechartdata(String sn, String startTime, String endTime) throws ParseException {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<LinechartApi> apis = new ArrayList<>();
        Timestamp start = null;
        Timestamp end = null;
        if (CheckNull.check(startTime)) {
            start = new Timestamp(sdf.parse(startTime).getTime());
        }
        if (CheckNull.check(endTime)) {
            end = new Timestamp(sdf.parse(endTime).getTime());
        }
        List<Devicedata> list = devicedataService.getlinechartdata(sn, start, end);
        for (Devicedata devicedata : list) {
            LinechartApi api = new LinechartApi();

            api.setTime(sdf.format(devicedata.getCreatedate()));
            api.setValue(devicedata.getReport());
            apis.add(api);
        }
        return apis;
    }

    @RequestMapping(value = "/getDeviceBySn")
    @ResponseBody
    public MapDeviceApi getDeviceBySn(String sn) {
        Jedis redis = RedisPoolUtils.getJedisObject();
        MapDeviceApi deviceApi;
        try {
            String s1 = redis.hget(RedisPoolUtils.dbname, sn);
            deviceApi = JSON.parseObject(s1, MapDeviceApi.class);
            if (deviceApi != null) {
                deviceApi.setSn(sn);
            }
        } finally {
            redis.close();
        }
        return deviceApi;
    }

    @RequestMapping(value = "/deviceDataBySn")
    @ResponseBody
    public List<Devicedata> deviceDataBySn(String sn) {
        Devicedata devicedata = new Devicedata();
        devicedata.setSn(sn);
        List<Devicedata> a = devicedataService.findByExampleEq(devicedata, "sn");
        return a;
    }


    @RequestMapping(value = "/deviceConf")
    @ResponseBody
    public Map<String, String> deviceConf(@RequestBody ConfApi confApi) {
        Map<String, String> info = new HashMap<>();
        info.put("content", "操作成功");
        info.put("Message", "ok");
        Jedis redis = RedisPoolUtils.getJedisObject();
        Map<String, String> map = new HashMap<>();
        try {
            Pipeline p = redis.pipelined();
            if (confApi.getAllDevices() != 0) {
                List<Device> list = deviceService.getList();
                for (Device dev : list) {
                    configInfo(dev, confApi, map);
                }
            } else if (confApi.getAllDevices() == null) {
                info.put("content", "参数错误");
                info.put("Message", "error");
                return info;
            } else {
                Device device = deviceService.get(confApi.getSn());
                configInfo(device, confApi, map);
            }
            p.hmset(RedisPoolUtils.fireConfig, map);
            p.sync();
            p.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            redis.close();
        }
        System.out.println(confApi.getAllDevices());
        return info;
    }

    private int configInfo(Device device, ConfApi confApi, Map<String, String> map) {
        Deviceconfig deviceconfig = new Deviceconfig();
        if (confApi.getUpperLimit() != null) {
            deviceconfig.setUpper(confApi.getUpperLimit());
        }
        if (confApi.getLowerLimit() != null) {
            deviceconfig.setLower(confApi.getLowerLimit());
        }
        if (CheckNull.check(confApi.getReport())) {
            deviceconfig.setReportCycle(confApi.getReport());
        }
        if (CheckNull.check(confApi.getSample())) {
            deviceconfig.setSampleCycle(confApi.getSample());
        }
        if (CheckNull.check(deviceconfig.getUpper()) || CheckNull.check(deviceconfig.getLower()) ||
                CheckNull.check(deviceconfig.getReportCycle()) || CheckNull.check(deviceconfig.getSampleCycle())) {
            deviceconfig.setDeviceBySn(device);
            deviceconfig.setCreatedate(new Timestamp(System.currentTimeMillis()));
            Serializable configId = deviceConfigService.insertT(deviceconfig);
            deviceconfig.setSn(deviceconfig.getDeviceBySn().getSn());
            deviceconfig.setDeviceBySn(null);
            String s = JSON.toJSONString(deviceconfig);
            map.put(configId.toString(), s);
            return 0;
        }
        return 1;

    }

    private void IPconfig(Device device, ConfApi confApi, Map<String, String> map) {
        Deviceconfig deviceconfig = new Deviceconfig();
        deviceconfig.setDeviceBySn(device);
        deviceconfig.setCreatedate(new Timestamp(System.currentTimeMillis()));
        deviceconfig.setNetconfig(confApi.getNetconfig());
        Serializable configId = deviceConfigService.insertT(deviceconfig);
        deviceconfig.setSn(device.getSn());
        String s = JSON.toJSONString(deviceconfig);
        map.put(configId.toString(), s);
    }


    private boolean isIP(String ip) {
        String regex = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
        return ip.matches(regex);
    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
